﻿using System;
using System.Data;
using System.Data.SqlClient;
using Company.BLL.WS.KDT.SXXK;
using Company.BLL.WS.SXXK;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using System.Xml;

namespace Company.BLL.KDT.SXXK
{
    public partial class SanPhamDangKy
    {
        private SanPhamCollection _SPCollection = new SanPhamCollection();

        public SanPhamCollection SPCollection
        {
            set { this._SPCollection = value; }
            get { return this._SPCollection; }
        }

        //-----------------------------------------------------------------------------------------
        public void LoadSPCollection()
        {
            this._SPCollection = SanPham.SelectCollectionBy_Master_ID(this.ID);
        }

        //-----------------------------------------------------------------------------------------

        public bool InsertUpdateFull()
        {
            bool ret;
            SqlDatabase db = (SqlDatabase)DatabaseFactory.CreateDatabase();
            using (SqlConnection connection = (SqlConnection)db.CreateConnection())
            {
                connection.Open();
                SqlTransaction transaction = connection.BeginTransaction();
                try
                {
                    if (this._ID == 0)
                        this._ID = this.InsertTransaction(transaction);
                    else
                        this.UpdateTransaction(transaction);

                    foreach (SanPham spDetail in this._SPCollection)
                    {
                        if (spDetail.ID == 0)
                        {
                            spDetail.Master_ID = this._ID;
                            spDetail.ID = spDetail.InsertTransaction(transaction);
                        }
                        else
                        {
                            spDetail.UpdateTransaction(transaction);
                        }
                    }
                    transaction.Commit();
                    ret = true;
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    throw new Exception(ex.Message);
                }
                finally
                {
                    connection.Close();
                }
            }
            return ret;
        }

        public void InsertUpdateFull(SqlTransaction transaction)
        {
            if (this._ID == 0)
                this._ID = this.InsertTransaction(transaction);
            else
                this.UpdateTransaction(transaction);

            foreach (SanPham spDetail in this._SPCollection)
            {
                if (spDetail.ID == 0)
                {
                    spDetail.Master_ID = this._ID;
                    spDetail.ID = spDetail.InsertTransaction(transaction);
                }
                else
                {
                    spDetail.UpdateTransaction(transaction);
                }
            }
        }

      
        #region WebService Methods của Softech
        //-----------------------------------------------------------------------------------------
        /// <summary>
        /// Kiểm tra sự tồn tại của các mã sản phẩm. 
        /// </summary>
        /// <returns>Danh sách sản phẩm đã tồn tại.</returns>
        public SanPhamCollection WSCheckExist()
        {
            // Chuẩn bị dữ liệu để gửi qua WEB SERVICE.
            SXXKService sxxkService = new SXXKService();
            string[] danhsachSP = new string[this.SPCollection.Count];
            for (int i = 0; i < this.SPCollection.Count; i++)
            {
                danhsachSP[i] = this.SPCollection[i].Ma;
            }
            string[] danhsachSPDaDangKy = sxxkService.SanPham_CheckExist(this.MaHaiQuan, this.MaDoanhNghiep, danhsachSP);

            // Dữ liệu trả về.
            SanPhamCollection collection = new SanPhamCollection();
            foreach (string s in danhsachSPDaDangKy)
            {
                foreach (SanPham sp in this.SPCollection)
                {
                    if (sp.Ma == s)
                    {
                        collection.Add(sp);
                        break;
                    }
                }
            }
            return collection;
        }

        //-----------------------------------------------------------------------------------------
        public long WSSend(ref string[] DanhSachDaDangKy)
        {
            // Chuẩn bị dữ liệu để gửi qua WEB SERVICE.
            // Lấy thông tin đăng ký.
            KDT_SXXK_Service kdtService = new KDT_SXXK_Service();
            SanPhamDangKyInfo webSPDangKyInfo = new SanPhamDangKyInfo();
            webSPDangKyInfo.MaHaiQuan = this._MaHaiQuan;
            webSPDangKyInfo.MaDoanhNghiep = this._MaDoanhNghiep;
            webSPDangKyInfo.MaDaiLy = this.MaDaiLy;
            webSPDangKyInfo.SoTiepNhan = this.SoTiepNhan;
            webSPDangKyInfo.NamTiepNhan =(short)this.NgayTiepNhan.Year;
            webSPDangKyInfo.NgayTiepNhan = this.NgayTiepNhan;
            // Lấy danh sách sản phẩm.
            int count = this._SPCollection.Count;
            webSPDangKyInfo.SPInfoCollection = new SanPhamInfo[count];
            int i = 0;
            foreach (SanPham spDetail in this._SPCollection)
            {
                SanPhamInfo webSPInfo = new SanPhamInfo();
                webSPInfo.MaHaiQuan = this._MaHaiQuan;
                webSPInfo.MaDoanhNghiep = this._MaDoanhNghiep;
                webSPInfo.Ma = spDetail.Ma;
                webSPInfo.Ten = spDetail.Ten;
                webSPInfo.MaHS = spDetail.MaHS;
                webSPInfo.DVT_ID = spDetail.DVT_ID;
                webSPDangKyInfo.SPInfoCollection[i] = webSPInfo;
                i++;
            }

            // Thực hiện gửi dữ liệu.
            this._SoTiepNhan = kdtService.SanPham_Send(webSPDangKyInfo, ref DanhSachDaDangKy);
            if (this._SoTiepNhan > 0)
            {
                this._TrangThaiXuLy = BLL.TrangThaiXuLy.CHO_DUYET;
                this._NgayTiepNhan = DateTime.Today;
                this.InsertUpdateFull();
            }
            return this._SoTiepNhan;
        }

        //-----------------------------------------------------------------------------------------
        /// <summary>
        /// Hủy thông tin khai báo.
        /// </summary>
        public bool WSCancel()
        {
            KDT_SXXK_Service kdtService = new KDT_SXXK_Service();
            bool result = kdtService.SanPham_Cancel(this._SoTiepNhan, this._MaHaiQuan, this._MaDoanhNghiep, this._NgayTiepNhan.Year);
            if (result)
            {
                // Trả lại trạng thái chưa khai báo.
                this.SoTiepNhan = 0;
                this.NgayTiepNhan = new DateTime(1900, 1, 1);
                this.TrangThaiXuLy = BLL.TrangThaiXuLy.CHUA_KHAI_BAO;
                this.Update();
            }
            return result;
        }

        //-----------------------------------------------------------------------------------------
        public void WSRequestStatus()
        {
            // Các bước thực hiện:
            // 1. Lấy thông tin từ Web Service.
            // 2. Cập nhật thông tin đăng ký.
            // 3. Xóa danh sách sản phẩm cũ.
            // 4. Cập nhật lại danh sách sản phẩm mới.
            // 5. Nếu trạng thái: Đã duyệt chính thức thì chuyển danh sách sản phẩm đã duyệt sang phân hệ SXXK.

            // 1. Lấy danh sách từ Web Service.
            KDT_SXXK_Service kdtService = new KDT_SXXK_Service();
            DataSet ds = kdtService.SanPham_RequestStatus(this._SoTiepNhan, this._MaHaiQuan, this._MaDoanhNghiep, Convert.ToInt16(this._NgayTiepNhan.Year));
            DataTable dt = ds.Tables[0];
            if (dt.Rows.Count > 0)
            {
                SqlDatabase db = (SqlDatabase)DatabaseFactory.CreateDatabase();
                using (SqlConnection connection = (SqlConnection)db.CreateConnection())
                {
                    connection.Open();
                    SqlTransaction transaction = connection.BeginTransaction();
                    try
                    {
                        // 2. Cập nhật thông tin đăng ký.
                        this._TrangThaiXuLy = Convert.ToInt32(dt.Rows[0]["TrangThaiXL"]);

                        // 3. Xóa danh sách sản phẩm cũ.
                        this.LoadSPCollection();
                        SanPham.DeleteCollection(this._SPCollection, transaction);
                        this.SPCollection.Clear();

                        // 4. Cập nhật lại danh sách sản phẩm mới.
                        int stt = 1;
                        foreach (DataRow row in dt.Rows)
                        {
                            SanPham sp = new SanPham();
                            sp.Master_ID = this._ID;
                            sp.Ma = row["Ma_SP"].ToString();
                            sp.Ten = row["Ten_SP"].ToString();
                            sp.MaHS = row["Ma_HS"].ToString();
                            sp.DVT_ID = row["Ma_DVT"].ToString();
                            sp.STTHang = stt++;
                            this._SPCollection.Add(sp);
                        }

                        // Cập nhật vào CSDL.
                        this.InsertUpdateFull(transaction);

                        // 5. Nếu trạng thái là đã duyệt chính thức thì chuyển danh sách sản phẩm đã duyệt sang phân hệ SXXK.
                        if (this._TrangThaiXuLy == BLL.TrangThaiXuLy.DA_DUYET)
                        {
                            foreach (DataRow row in dt.Rows)
                            {
                                BLL.SXXK.SanPham sp = new BLL.SXXK.SanPham();
                                sp.MaHaiQuan = this._MaHaiQuan;
                                sp.MaDoanhNghiep = this._MaDoanhNghiep;
                                sp.Ma = row["Ma_SP"].ToString();
                                sp.Ten = row["Ten_SP"].ToString();
                                sp.MaHS = row["Ma_HS"].ToString();
                                sp.DVT_ID = row["Ma_DVT"].ToString();

                                sp.InsertUpdateTransaction(transaction);
                            }
                        }

                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        throw new Exception(ex.Message);
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }
            else
            {
                this.Update();
            }
        }
        #endregion WebService Methods của Softech

        #region WebService Methods của Hải quan
        private string ConfigPhongBi(int type, int function)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("TemplateXML\\PhongBi.xml");
            //set thong tin hai quan den
            XmlNode nodeTo = doc.GetElementsByTagName("To")[0];
            XmlNode nodeName = nodeTo.ChildNodes[0];
            nodeName.InnerText = Company.BLL.DuLieuChuan.DonViHaiQuan.GetName(this._MaHaiQuan);
            XmlNode nodeIdentity = nodeTo.ChildNodes[1];
            nodeIdentity.InnerText = this.MaHaiQuan;

            ////set thong so gui di subject
            XmlNode nodeSubject = doc.GetElementsByTagName("Subject")[0];
            XmlNode nodeType = nodeSubject.ChildNodes[0];
            nodeType.InnerText = type.ToString();

            XmlNode nodeFunction = nodeSubject.ChildNodes[1];
            nodeFunction.InnerText = function.ToString();

            XmlNode nodeReference = nodeSubject.ChildNodes[2];
            nodeReference.InnerText = (System.Guid.NewGuid().ToString());

            XmlNode nodeMessageID = doc.GetElementsByTagName("messageId")[0];
            nodeMessageID.InnerText = (System.Guid.NewGuid().ToString());
          
            return doc.InnerXml;
        }
   
        #region Khai báo danh sách sản phẩm
        public string WSSendXML(string pass)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(ConfigPhongBi(MessgaseType.DanhMucSanPham, MessgaseFunction.KhaiBao));
            XmlDocument docNPL = new XmlDocument();
            docNPL.LoadXml(ConvertCollectionToXML());


            //luu vao string
            XmlNode root = docNPL.GetElementsByTagName("Root")[0].CloneNode(true);
            XmlNode Content = doc.GetElementsByTagName("Content")[0];
            XmlNode root2 = doc.CreateElement("Root");
            root2.InnerXml = root.InnerXml;
            Content.AppendChild(root2);
            WS.KhaiDienTu.KDTService kdt = new Company.BLL.WS.KhaiDienTu.KDTService();
            string kq = kdt.Send(doc.InnerXml, pass);
            return kq;
        }
        private string ConvertCollectionToXML()
        {
            //load du lieu
            XmlDocument docNPL = new XmlDocument();
            docNPL.Load("TemplateXML\\KhaiBaoSanPham.xml");
            XmlNode nplNode = docNPL.GetElementsByTagName("SP")[0];
            XmlNode nodeHQNhan = docNPL.GetElementsByTagName("HQ_NHAN")[0];
            nodeHQNhan.Attributes["MA_HQ"].Value = this.MaHaiQuan;
            nodeHQNhan.Attributes["TEN_HQ"].Value = Company.BLL.DuLieuChuan.DonViHaiQuan.GetName(this._MaHaiQuan);

            if (this.SPCollection == null || this.SPCollection.Count == 0)
            {
                this.SPCollection = SanPham.SelectCollectionBy_Master_ID(this.ID);
            }
            foreach (SanPham sp in this.SPCollection)
            {
                XmlNode node = docNPL.CreateElement("SP.ITEM");
                XmlAttribute sttAtt = docNPL.CreateAttribute("STT");
                sttAtt.Value = sp.STTHang.ToString();
                node.Attributes.Append(sttAtt);

                XmlAttribute maAtt = docNPL.CreateAttribute("MA_SP");
                maAtt.Value = sp.Ma;
                node.Attributes.Append(maAtt);

                XmlAttribute MaHSAtt = docNPL.CreateAttribute("MA_HS");
                MaHSAtt.Value = sp.MaHS;
                node.Attributes.Append(MaHSAtt);

                XmlAttribute TenAtt = docNPL.CreateAttribute("TEN_SP");
                TenAtt.Value = sp.Ten;
                node.Attributes.Append(TenAtt);

                XmlAttribute DVTAtt = docNPL.CreateAttribute("MA_DVT");
                DVTAtt.Value = sp.DVT_ID;
                node.Attributes.Append(DVTAtt);

                nplNode.AppendChild(node);
            }
            return docNPL.InnerXml;
        }
        #endregion Khai báo danh sách nguyên phụ liệu

        #region Huy khai báo danh mục nguyên phụ liệu

        public string WSCancelXML(string pass)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(ConfigPhongBi(MessgaseType.DanhMucSanPham, MessgaseFunction.HuyKhaiBao));

            XmlDocument docNPL = new XmlDocument();
            docNPL.Load("TemplateXML\\HuyKhaiBaoSanPham.xml");

            XmlNode nodeHQNhan = docNPL.GetElementsByTagName("HQ_NHAN")[0];
            nodeHQNhan.Attributes["MA_HQ"].Value = this.MaHaiQuan;
            nodeHQNhan.Attributes["TEN_HQ"].Value = Company.BLL.DuLieuChuan.DonViHaiQuan.GetName(this._MaHaiQuan);

            XmlNode nodeDuLieu = docNPL.GetElementsByTagName("DU_LIEU")[0];
            nodeDuLieu.Attributes["SO_TN"].Value = this.SoTiepNhan.ToString();
            nodeDuLieu.Attributes["NAM_TN"].Value = this.NgayTiepNhan.Year.ToString();

            XmlNode root = docNPL.GetElementsByTagName("Root")[0].CloneNode(true);
            XmlNode Content = doc.GetElementsByTagName("Content")[0];
            XmlNode root2 = doc.CreateElement("Root");

            root2.InnerXml = root.InnerXml;
            Content.AppendChild(root2);
            WS.KhaiDienTu.KDTService kdt = new Company.BLL.WS.KhaiDienTu.KDTService();
            string kq = kdt.Send(doc.InnerXml, pass);
            return kq;

        }

        #endregion Huy khai báo danh mục nguyên phụ liệu

        #region Lấy phản hồi

        public string WSRequestXML(string pass)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(ConfigPhongBi(MessgaseType.DanhMucSanPham, MessgaseFunction.LayPhanHoi));

            XmlDocument docNPL = new XmlDocument();
            docNPL.Load("TemplateXML\\LayPhanHoiSanPham.xml");

            XmlNode nodeHQNhan = docNPL.GetElementsByTagName("HQ_NHAN")[0];
            nodeHQNhan.Attributes["MA_HQ"].Value = this.MaHaiQuan;
            nodeHQNhan.Attributes["TEN_HQ"].Value = Company.BLL.DuLieuChuan.DonViHaiQuan.GetName(this._MaHaiQuan);

            XmlNode nodeDuLieu = docNPL.GetElementsByTagName("DU_LIEU")[0];
            nodeDuLieu.Attributes["SO_TN"].Value = this.SoTiepNhan.ToString();
            nodeDuLieu.Attributes["NAM_TN"].Value = this.NgayTiepNhan.Year.ToString();

            XmlNode root = docNPL.GetElementsByTagName("Root")[0].CloneNode(true);
            XmlNode Content = doc.GetElementsByTagName("Content")[0];
            XmlNode root2 = doc.CreateElement("Root");

            root2.InnerXml = root.InnerXml;
            Content.AppendChild(root2);

            WS.KhaiDienTu.KDTService kdt = new Company.BLL.WS.KhaiDienTu.KDTService();
            string kq = kdt.Request(doc.InnerXml, pass);
            return kq;

        }

        #endregion Lấy phản hồi
        #endregion của hải quan

        #region Webservice của FPT

        #region Khai báo danh sách sản phẩm        
        //cap nhat
        public string WSUpdateXMLFPT(string pass, SanPhamCollection spCollection)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("FPTService\\SXXK_SP_CAPNHAT.xml");

            //luu thong tin gui
            XmlNode hq = doc.GetElementsByTagName("Root/SXXK/THONG_TIN/HQ_NHAN")[0];
            hq.Attributes["MA_HQ"].Value = this.MaHaiQuan;
            hq.Attributes["TEN_HQ"].Value = Company.BLL.DuLieuChuan.DonViHaiQuan.GetName(this.MaHaiQuan);

            XmlNode data = doc.SelectSingleNode("Root/SXXK/THONG_TIN/DU_LIEU");
            data.Attributes["SO_DK"].Value = this.SoTiepNhan.ToString();


            XmlNode spNode = doc.GetElementsByTagName("SP")[0];
            foreach (SanPham sp in spCollection)
            {
                XmlNode node = doc.CreateElement("SP.ITEM");
                XmlAttribute sttAtt = doc.CreateAttribute("STT");
                sttAtt.Value = sp.STTHang.ToString();
                node.Attributes.Append(sttAtt);

                XmlAttribute maAtt = doc.CreateAttribute("MA_SP");
                maAtt.Value = sp.Ma;
                node.Attributes.Append(maAtt);

                XmlAttribute MaHSAtt = doc.CreateAttribute("MA_HS");
                MaHSAtt.Value = sp.MaHS;
                node.Attributes.Append(MaHSAtt);

                XmlAttribute TenAtt = doc.CreateAttribute("TEN_SP");
                TenAtt.Value = sp.Ten;
                node.Attributes.Append(TenAtt);                

                XmlAttribute DVTAtt = doc.CreateAttribute("MA_DVT");
                DVTAtt.Value = sp.DVT_ID;
                node.Attributes.Append(DVTAtt);
                spNode.AppendChild(node);
            }
            WS.FPT.SXXK.SXXKService service = new Company.BLL.WS.FPT.SXXK.SXXKService();
            string kq = service.DataProcess(doc.InnerXml, "ecusxgeiyklgA\\SmqUK@rbiqDyAgbXBIlBTUTL;", pass);
            return kq;
        }

        //dang ky
        public string WSSendXMLFPT(string pass)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("FPTService\\SXXK_SP_DK.xml");

            //luu thong tin gui
            XmlNode hq = doc.SelectSingleNode("Root/SXXK/THONG_TIN/HQ_NHAN");
            hq.Attributes["MA_HQ"].Value = this.MaHaiQuan;
            hq.Attributes["TEN_HQ"].Value = Company.BLL.DuLieuChuan.DonViHaiQuan.GetName(this.MaHaiQuan);

            XmlNode spNode = doc.SelectSingleNode("Root/SXXK/DU_LIEU/SP");
            if (this.SPCollection == null || this.SPCollection.Count == 0)
            {
                this.SPCollection = SanPham.SelectCollectionBy_Master_ID(this.ID);
            }
            foreach (SanPham sp in this.SPCollection)
            {
                XmlNode node = doc.CreateElement("SP.ITEM");
                XmlAttribute sttAtt = doc.CreateAttribute("STT");
                sttAtt.Value = sp.STTHang.ToString();
                node.Attributes.Append(sttAtt);

                XmlAttribute maAtt = doc.CreateAttribute("MA_SP");
                maAtt.Value = sp.Ma;
                node.Attributes.Append(maAtt);

                XmlAttribute MaHSAtt = doc.CreateAttribute("MA_HS");
                MaHSAtt.Value = sp.MaHS;
                node.Attributes.Append(MaHSAtt);

                XmlAttribute TenAtt = doc.CreateAttribute("TEN_SP");
                TenAtt.Value = sp.Ten;
                node.Attributes.Append(TenAtt);

                XmlAttribute DVTAtt = doc.CreateAttribute("MA_DVT");
                DVTAtt.Value = sp.DVT_ID;
                node.Attributes.Append(DVTAtt);
                spNode.AppendChild(node);
            }
            WS.FPT.SXXK.SXXKService service = new Company.BLL.WS.FPT.SXXK.SXXKService();
            string kq = service.DataProcess(doc.InnerXml, "ecusxgeiyklgA\\SmqUK@rbiqDyAgbXBIlBTUTL;", pass);
            return kq;
      
        }

        #endregion Khai báo danh sách sản phẩm

        #region Hủy khai báo danh sách sản phẩm
      
        //huy dang ky
        public string WSHuyXMLFPT(string pass)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("FPTService\\SXXK_SP_HUY.xml");

            //luu thong tin gui
            XmlNode data = doc.SelectSingleNode("Root/SXXK/DU_LIEU");
            data.Attributes["SO_DK"].Value = this.MaHaiQuan;
            XmlNode hq = doc.SelectSingleNode("Root/SXXK/THONG_TIN/HQ_NHAN");
            hq.Attributes["MA_HQ"].Value = this.MaHaiQuan;
            hq.Attributes["TEN_HQ"].Value = Company.BLL.DuLieuChuan.DonViHaiQuan.GetName(this.MaHaiQuan);

            WS.FPT.SXXK.SXXKService service = new Company.BLL.WS.FPT.SXXK.SXXKService();
            string kq = service.DataProcess(doc.InnerXml, "ecusxgeiyklgA\\SmqUK@rbiqDyAgbXBIlBTUTL;", pass);
            return kq;
        }

        #endregion Hủy khai báo danh sách sản phẩm

        #region Lấy thông tin trả lời từ hải quan

        //lây thong tin dang ky
        public string WSRequestXMLFPT(string pass)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("FPTService\\SXXK_TRALOI_DK.xml");

            //luu thong tin gui
            XmlNode dangkyType = doc.SelectSingleNode("Root/SXXK");
            dangkyType.Attributes["TRA_LOI"].Value = "DANG_KY_SP";
            XmlNode hq = doc.SelectSingleNode("Root/SXXK/THONG_TIN/HQ_NHAN");
            hq.Attributes["MA_HQ"].Value = this.MaHaiQuan;
            hq.Attributes["TEN_HQ"].Value = Company.BLL.DuLieuChuan.DonViHaiQuan.GetName(this.MaHaiQuan);

            XmlNode data = doc.SelectSingleNode("Root/SXXK/DU_LIEU");
            data.Attributes["SO_DK"].Value = this.SoTiepNhan.ToString();
            WS.FPT.SXXK.SXXKService service = new Company.BLL.WS.FPT.SXXK.SXXKService();          
            string kq = service.DataProcess(doc.InnerXml, "ecusxgeiyklgA\\SmqUK@rbiqDyAgbXBIlBTUTL;", pass);
            return kq;
        }

        #endregion Lấy thông tin trả lời từ hải quan
        #endregion Webservice của FPT

    }
}